package com.jzw.controller;

import com.jzw.pojo.Users;
import com.jzw.pojo.bo.UserBo;
import com.jzw.service.UserService;
import com.jzw.utils.IMOOCJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;

@Api(value = "注册登录", tags = {"用于注册登录的相关接口"})
@RestController
@RequestMapping("/passport")
public class PassportController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户名是否存在", notes = "检测用户名是否存在")
    @GetMapping("/userNameIsExist")
    public IMOOCJSONResult userNameIsExist(@RequestParam String userName) {
        if (StringUtils.isBlank(userName)) {
            return IMOOCJSONResult.errorMsg("用户名不能为空");
        }
        //用户名没有重复返回200 否则返回500
        return userService.queryUserNameIsExist(userName) ? IMOOCJSONResult.errorMsg("用户名已经存在") : IMOOCJSONResult.ok();
    }

    @PostMapping("/regist")
    public IMOOCJSONResult regist(@RequestBody UserBo userBo) {
        if (userBo == null) {
            return IMOOCJSONResult.errorMsg("请求参数非法");
        }
        else if (StringUtils.isBlank(userBo.getUsername())) {
            return IMOOCJSONResult.errorMsg("用户名不能为空");
        }
        else if (StringUtils.isBlank(userBo.getPassword())) {
            return IMOOCJSONResult.errorMsg("密码不能为空");
        }
        else if (StringUtils.isBlank(userBo.getConfirmPassword())) {
            return IMOOCJSONResult.errorMsg("确认密码不能为空");
        }
        else if (!userBo.getPassword().equals(userBo.getConfirmPassword())) {
            return IMOOCJSONResult.errorMsg("两次输入的密码不一致");
        }
        else if (userService.queryUserNameIsExist(userBo.getUsername())) {
            return IMOOCJSONResult.errorMsg("用户名已经存在");
        }

        try {
            Users user = userService.createUser(userBo);

            return IMOOCJSONResult.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
            return IMOOCJSONResult.errorMsg(e.getMessage());
        }
    }

}
